package cn.tedu.test.charging.emqx.config;

import cn.tedu.test.charging.emqx.mqtt.EmqxDemoConsumer;
import cn.tedu.test.charging.emqx.mqtt.MqttContext;
import cn.tedu.test.charging.emqx.mqtt.OrderMapper;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 在容器中创建mqtt客户端 连接 1883 emqx
 * 实现 生产 消费
 */
@Configuration
public class MqttClientConfiguration {
    /*@Autowired
    private EmqxDemoConsumer emqxDemoConsumer;*/
    @Autowired
    private MqttContext mqttContext;
   /* @Autowired
    private OrderMapper orderMapper;*/
    @Bean
    public MqttClient mqttClient(){
        MqttClient mqttClient = null;
        //考虑连接不上,emqx没启动 端口不对没有服务端 连接失败等问题
        try{
            //初始化client对象 提供给他必要的连接属性 ip port amdin public
            //客户端建立后 每次启动都会在本地 存储一个日志 锁文件 将这个文件内容 放到内存
            mqttClient=
            new MqttClient("tcp://192.168.8.100:1883","demo-client",
                    new MemoryPersistence());
            //准备客户端额外的参数和选项 比如 用户名密码 比如自动连接 等待超时时间
            MqttConnectOptions options=new MqttConnectOptions();
            options.setUserName("admin");
            options.setPassword("public".toCharArray());
            //作为了解
            //options.setCleanSession(true);
            //options.setKeepAliveInterval(30);
            //options.setConnectionTimeout(30);
            //options.setAutomaticReconnect(true);
            //通过选项建立client客户端和服务端连接
            //如果客户端只是生产消息,现在的参数就足够了,但是如果客户端负责消费监听 需要一个consumer回调对象
            mqttClient.setCallback(new EmqxDemoConsumer(mqttClient,mqttContext));
            mqttClient.connect(options);
        }catch (Exception e){
            System.out.println("客户端创建失败,无法实现有效对象使用");
        }
        return mqttClient;
    }
}
